/*
 * @Author: yanjikun
 * @Date: 2022-04-21 15:11:03
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-04-22 09:39:02
 * @Description: file content
 */

import BasicForm, { BasicProps } from '@/components/Form'
import { FormActionType } from '@/components/Form/src/types/form'
import { nextTick, ref, unref } from 'vue'
import { FormModalProps } from './types'
import { useModal } from './useModal'

interface ShowModalProps<T = Recordable> {
  modalProps: FormModalProps<T>
  formProps: Partial<BasicProps>
}
export const useFormModal = function <T = any>() {
  const [ModalRender] = useModal()

  const showModal = async <P extends T>({ modalProps, formProps }: ShowModalProps<P>) => {
    const formRef = ref<FormActionType>()
    const onCancel = (e: MouseEvent) => {
      formRef.value?.resetFields()
      modalProps?.onCancel?.(e)
    }

    await ModalRender.show({
      destroyOnClose: true,
      ...modalProps,
      onCancel,
      content: () => {
        const _formProps = Object.assign({}, { showActionButtonGroup: false }, formProps)
        return <BasicForm ref={formRef} {..._formProps}></BasicForm>
      },
      onOk: async () => {
        let values: any
        try {
          values = await unref(formRef)?.handleSubmit()
          if (!values) {
            return Promise.reject()
          }
          await modalProps?.onFinish?.(values)
          unref(formRef)?.resetFields()
        } catch (error) {
          modalProps?.onFail?.(values)
          return Promise.reject(error)
        }
      }
    })

    await nextTick()
    return [unref(formRef)] as const
  }
  return [showModal, ModalRender] as const
}
